/**
 * 简介：完成对Roslib.js的封装，实现ROS链接开关的方法
 */
import ROSLIB from "roslib";
import { store } from "../state/store";

/**
 * 链接地址
 */
const defaultUrl = "ws://";

/**
 * ros连接,模块唯一值
 * 初始为空值，不连接任何地址
 */
var ros = new ROSLIB.Ros();

/**
 * 在ros对象中创建一个链接
 * @param { string }URL: 连接的地址
 */
function createConnect(URL = defaultUrl) {
  // 建立连接
  ros.connect(URL);
  // 存储
  store.setUrlAction(URL);
  // 添加状态监听
  ros.on("connection", function () {
    console.log("ROS in connect.js: Connected to websocket server.");
    store.setStatusAction("Connected");
  });

  ros.on("error", function (error) {
    console.log(
      "ROS in connect.js: Error connecting to websocket server: ",
      error
    );
    store.setStatusAction("Error");
  });

  ros.on("close", function () {
    console.log("ROS in connect.js: Connection to websocket server closed.");
    store.setStatusAction("Closed");
  });
}

/**
 * 在当前已有连接的情况下,连接新地址
 * @param URL: 重连的地址
 */
function reconnect(URL) {
  ros.close();
  ros.connect(URL);
  // 存储
  store.setUrlAction(URL);
}

// 关闭连接
function close() {
  ros.close();
  // 清除存储
  store.clearStoreAction();
}

/**
 * 获取当前状态
 */
function getRosConnectStatus() {
  const state = { 0: "CONNECTING", 1: "OPEN", 2: "CLOSING", 3: "CLOSED" };
  var t = ros.socket.readyState;
  if (t) {
    return state[t];
  } else {
    console.log("getRosConnectStatus: error");
    return "getRosConnectStatus: error";
  }
}


export { ros, createConnect, reconnect, close, getRosConnectStatus };
